package online.heycm.platform.uid;

import com.baidu.fsg.uid.UidGenerator;
import com.baidu.fsg.uid.impl.CachedUidGenerator;
import com.baidu.fsg.uid.worker.DisposableWorkerIdAssigner;
import com.baidu.fsg.uid.worker.WorkerIdAssigner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

/**
 * @author heycm
 * @since 2023/11/26 17:52
 */
@Configuration
@ConditionalOnProperty(value = "snowflake.unique-worker-id")
public class UidAutoConfiguration {

    @Value("${snowflake.unique-worker-id}")
    private long uniqueWorkerId;

    @Bean
    public UidGenerator uidGenerator() {
        Assert.isTrue(uniqueWorkerId > 0, "Invalid uniqueWorkerId: " + uniqueWorkerId);
        WorkerIdAssigner workerIdAssigner = new DisposableWorkerIdAssigner(uniqueWorkerId);
        return new CachedUidGenerator(workerIdAssigner);
    }

    @Bean
    public UidService uidService(UidGenerator uidGenerator) {
        return new UidServiceImpl(uidGenerator);
    }

    //public static void main(String[] args) throws Exception {
    //    WorkerIdAssigner workerIdAssigner = new DisposableWorkerIdAssigner(1);
    //    CachedUidGenerator uidGenerator = new CachedUidGenerator(workerIdAssigner);
    //    uidGenerator.afterPropertiesSet();
    //    UidServiceImpl uidService = new UidServiceImpl(uidGenerator);
    //
    //    long l = System.currentTimeMillis();
    //    for (int i = 0; i < 100000; i++) {
    //        long nextId = uidService.nextId();
    //        System.out.println("nextId = " + nextId);
    //    }
    //    System.out.println("耗时: " + (System.currentTimeMillis()-l) + "ms");
    //
    //}
}
